/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.hazardsource.controller;

import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.hazardsource.domain.HazardSource;
import com.koron.hazardsource.domain.StandardRisk;
import com.koron.hazardsource.service.api.HazardSourceService;
import com.koron.hazardsource.util.BusinessCode;
import com.koron.system.annotation.Log;
import com.koron.system.discrete.BusinessManipulation;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "hazardSource", description = "标准危险源接口类")
@RestController
@RequestMapping("/hazardSource")
public class HazardSourceController {

    private final static  Logger logger = LoggerFactory.getLogger(HazardSourceController.class);

    @Autowired
    private HazardSourceService sourceService;

    /*@ApiOperation("保存危险源和所属风险项")
    @RequestMapping(value = "/saveSourceAndRisk.htm", method = { RequestMethod.POST })
    @ResponseBody
    public MessageBean<Boolean> saveSourceAndRisk(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestBody HazardSourceAndRisk sourceAndRisk){
        MessageBean<Boolean> msg=sourceService.saveSourceAndRisk(sourceAndRisk,user);
        return msg;
    }*/

    @ApiOperation("保存草稿")
    @RequestMapping(value = "/saveSourceAndRiskDraft.htm", method = {RequestMethod.POST})
    @Log(title = "新增、修改危险源保存草稿", businessModule = "标准危险源", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<?> saveSourceAndRiskDraft(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestBody List<HazardSource> hsList) {
        if(user==null){
            MessageBean<?>msg=new MessageBean<>();
            msg.setCode(BusinessCode.MESSAGE_CODE_ACTION_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_ACTION_EXCEPTION);
            return msg;
        }
        MessageBean<?> msg = sourceService.saveSourceAndRiskDraft(hsList, user);
        return msg;
    }

    @ApiOperation("提交操作")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "title", value = "标题", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "note", value = "说明", paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/submitSourceAndRisk.htm", method = {RequestMethod.POST})
    @Log(title = "新增、修改危险源提交操作", businessModule = "标准危险源", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<?> submitSourceAndRisk(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestBody List<HazardSource> hsList, String title, String note) {
        if(user==null){
            MessageBean<?>msg=new MessageBean<>();
            msg.setCode(BusinessCode.MESSAGE_CODE_ACTION_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_ACTION_EXCEPTION);
            return msg;
        }
        setProperties(hsList, user);
        MessageBean<?> msg = sourceService.submitSourceAndRisk(hsList, user, title, note);
        return msg;
    }

    private void setProperties(List<HazardSource> hsList, StaffBean user) {
        if (hsList != null && !hsList.isEmpty() && user != null) {
            Date date = new Date();
            hsList.stream().forEach(source -> {
                source.setAddTime(date);
                source.setAddUser(user.getCode());
                source.setAddUserName(user.getName());
                source.setUpdateTime(date);
                source.setUpdateUser(user.getCode());
                source.setUpdateUserName(user.getName());
                List<StandardRisk> risks = source.getRisks();
                if (risks != null && !risks.isEmpty()) {
                    risks.stream().forEach(risk -> {
                        risk.setAddTime(date);
                        risk.setAddUser(user.getCode());
                        risk.setAddUserName(user.getName());
                        risk.setUpdateTime(date);
                        risk.setUpdateUser(user.getCode());
                        risk.setUpdateUserName(user.getName());
                    });
                }
            });
        }
    }

    @ApiOperation("废弃危险源")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "title", value = "标题", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "note", value = "说明", paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/discard.htm", method = {RequestMethod.POST})
    @Log(title = "废弃危险源", businessModule = "标准危险源", businessManipulation = BusinessManipulation.UPDATE)
    public MessageBean<Boolean> discard(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(value = "idList") List<String> idList, String title, String note) {
        if(user==null){
            MessageBean<Boolean>msg=new MessageBean<>();
            msg.setCode(BusinessCode.MESSAGE_CODE_ACTION_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_ACTION_EXCEPTION);
            return msg;
        }
        MessageBean<Boolean> msg = sourceService.discard(idList, user, title, note);
        return msg;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    @ApiOperation("根据指定条件获取危险源分页列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "危险源名称", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "indicationLevelId", value = "危险源级别指标", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "riskLevelStart", value = "风险等级", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "riskLevelEnd", value = "风险等级", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "businessTypeId", value = "业态类型", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "hazardTypeId", value = "危险源类型", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "fitAllBusiness", value = "是否通用", paramType = "query", dataType = "Boolean"),
            @ApiImplicitParam(name = "state", value = "危险源状态", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "page", value = "当前页", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query", dataType = "Integer")
    })
    @RequestMapping(value = "/list.htm", method = {RequestMethod.GET})
    public MessageBean<?> list(@RequestParam(required = false) final String name, @RequestParam(required = false) final String indicationLevelId,
    				   @RequestParam(required = false) final Integer riskLevelStart,@RequestParam(required = false) final Integer riskLevelEnd,
    				   @RequestParam(required = false) final String businessTypeId,@RequestParam(required = false) final String hazardTypeId,
    				   @RequestParam(required = false) final Boolean fitAllBusiness,@RequestParam(required = false) final Integer state,
    				   @RequestParam Integer page, @RequestParam Integer pageSize) {
        MessageBean<DataBean> msg = new MessageBean<>();
        Integer totalPage = null;
	    Integer totalNumber = null;
	    Integer start = null;
	    Integer end = null;
	    if (null!=page && pageSize!=null){
            if (page >0 && pageSize > 0){
            }else{
            	//第一页 10条数据
            	page =1;
            	pageSize=10;
            }
            start=(page<=1)?0:(page-1)*pageSize;
            end = pageSize;
        }
        List<HazardSource> list = sourceService.queryByCondition("hazard_source", name, indicationLevelId,riskLevelStart,riskLevelEnd, businessTypeId, hazardTypeId, fitAllBusiness, state, start, end);
        totalNumber = sourceService.countByCondition("hazard_source", name, indicationLevelId,riskLevelStart,riskLevelEnd, businessTypeId, hazardTypeId, fitAllBusiness, state);
        if(start != null && end != null){
			totalPage = (totalNumber+pageSize-1)/pageSize;
		}else{
			totalPage = 1;
			page = totalPage;
			pageSize = totalNumber;
		}
        DataBean dataBean = new DataBean<>();
        dataBean.setList(list);
        dataBean.setTotalNumber(totalNumber);
        dataBean.setTotalPage(totalPage);
        msg.setCode(0);
        msg.setDescription("获取标准危险源列表成功");
        msg.setData(dataBean);
        return msg;
    }

    @ApiOperation("根据主键获取危险源详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "危险源Id", paramType = "query", dataType = "String"),
    })
    @RequestMapping(value = "/details.htm", method = {RequestMethod.GET})
    public MessageBean<HazardSource> details(@RequestParam final String id) {
        MessageBean<HazardSource> msg = new MessageBean<>();
        if (StringUtils.isEmpty(id)) {
            msg.setCode(11002);
            msg.setDescription("未选中数据，无法查看详情");
            return msg;
        }
        HazardSource source = sourceService.queryOneById("hazard_source", id);
        msg.setCode(0);
        msg.setDescription("获取标准危险源详情成功");
        msg.setData(source);
        return msg;
    }

    @ApiOperation("导出危险源")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "危险源名称", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "indicationLevelId", value = "危险源级别指标", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "riskLevelStart", value = "风险等级", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "riskLevelEnd", value = "风险等级", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "businessTypeId", value = "业态类型", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "hazardTypeId", value = "危险源类型", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "fitAllBusiness", value = "是否通用", paramType = "query", dataType = "Boolean"),
            @ApiImplicitParam(name = "state", value = "危险源状态", paramType = "query", dataType = "Integer"),
    })
    @RequestMapping(value = "/exportsHazardSource.htm", method = {RequestMethod.GET})
    public HttpEntity<?> exportsHazardSource(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                             String name, String indicationLevelId,Integer riskLevelStart,Integer riskLevelEnd,  String businessTypeId, String hazardTypeId, Boolean fitAllBusiness, Integer state) {
        List<HazardSource> list = sourceService.queryByCondition("hazard_source", name, indicationLevelId,riskLevelStart,riskLevelEnd, businessTypeId, hazardTypeId, fitAllBusiness, state, null, null);
        Map<String, Object> map = new HashMap<>();
        map.put("data", list);
        File targetFile = new File("static/excel/hazardSourceExport.xlsx");
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/hazardSourceExport.xlsx");
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }

        return Excel.createFile("危险源列表", targetFile, "hazardSourceExport.btl", map);
    }


    @ApiOperation(value = "下载危险源excel模板")
    @RequestMapping(value = "/downloadtemplate.htm", method = {RequestMethod.GET})
    @ResponseBody
    public HttpEntity<?> downloadTemplate() {
        Map<String, Object> map = new HashMap<>();
        File targetFile = new File("static/excel/hazardSourceTemplate.xlsx");
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/hazardSourceTemplate.xlsx");
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return Excel.createFile("危险源模板", targetFile, "default.btl", map);
    }

    @ApiOperation("标准危险源导入")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "title", value = "标题", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "note", value = "备注", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "file", value = "上传的excel文件", required = true, paramType = "query", dataType = "file"),
    })
    @RequestMapping(value = "/importEcxel.htm", method = {RequestMethod.POST})
    @Log(title = "标准危险源导入", businessModule = "标准危险源", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<?> importEcxel(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                            @RequestParam final String title,
                                            @RequestParam final String note, MultipartFile file) {
        MessageBean<?> msg = new MessageBean<>();
        try {
            if(user==null){
                msg.setCode(BusinessCode.MESSAGE_CODE_ACTION_EXCEPTION);
                msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_ACTION_EXCEPTION);
                return msg;
            }
            msg = sourceService.importFromExcel(user, file, title, note);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(-1);
            msg.setDescription("发生异常");
            return msg;
        }
    }

    @ApiOperation("标准危险源草稿列表")
    @RequestMapping(value = "/getDraftList.htm", method = {RequestMethod.GET})
    public MessageBean<?> getDraftList(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user) {
        if(user==null){
            MessageBean<?>msg=new MessageBean<>();
            msg.setCode(BusinessCode.MESSAGE_CODE_ACTION_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_ACTION_EXCEPTION);
            return msg;
        }
        return sourceService.getDraftList(user);
    }

    @ApiOperation("历史版本")
    @ApiImplicitParam(name = "code", value = "危险源code", required = true, paramType = "query", dataType = "String")
    @RequestMapping(value = "/getHistoryList.htm", method = {RequestMethod.GET})
    public MessageBean<?> getHistoryList(String code) {
        return sourceService.getHistoryList(code);
    }

    @ApiOperation("流程中的业务数据")
    @ApiImplicitParam(name = "ids", value = "流程关联的业务ids", required = true, paramType = "query", dataType = "String")
    @RequestMapping(value = "/getProcessData.htm", method = {RequestMethod.GET})
    public MessageBean<?> getProcessData(String ids) {
        return sourceService.getProcessData(ids);
    }


    @ApiOperation("删除草稿")
	@ApiImplicitParam(name = "id", value = "id", paramType = "query", dataType = "String")
    @RequestMapping(value = "/deleteDraft.htm", method = { RequestMethod.GET })
	public MessageBean<?> deleteDraft(String id){
		return sourceService.deleteDraft(id);
	}
}
